﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Kugar.Core.BaseStruct;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Kugar.Tool.DataSync.Server
{
    /// <summary>
    /// 使用默认Http传输方式,对接默认客户端,需实现GetAppIDHost函数,用于返回客户端对应的地址,
    /// 实现后,只需标识为导出组件即可
    /// </summary>
    public abstract class DefaultExporterPlugin:IExporterPlugin
    {
        public ResultReturn Export(string appID, string dataTypeName, JObject data)
        {
            var host = GetAppIDHost(appID);

            if (!host.StartsWith("http://",StringComparison.CurrentCultureIgnoreCase))
            {
                host = "http://" + host;
            }

            using (var client = new WebClient())
            {
                client.BaseAddress = host;

                try
                {
                    var u =
                        $"{host}/{appID}/{WebUtility.UrlEncode(dataTypeName)}";

                    var ret = client.UploadString(u, "POST", data.ToString(Formatting.None));

                    return JsonConvert.DeserializeObject<ResultReturn>(ret);
                }
                catch (Exception ex)
                {
                    return new FailResultReturn(ex);
                }
            }
        }

        public bool CanHandleWith(string appID, string dataTypeName)
        {
            return string.IsNullOrWhiteSpace(GetAppIDHost(appID));
        }

        /// <summary>
        /// 获取指定AppID的地址和端口号,返回数据的格式为 {域名/IP}:{端口号}
        /// </summary>
        /// <param name="appID"></param>
        /// <returns></returns>
        protected abstract string GetAppIDHost(string appID);
    }
}
